package main

import (
import (
	"fmt"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	CreditCards []CreditCard `gorm:"foreignKey:UserRefer"`
}

func (u *User) TableName()string  {
	return "user"
}

type CreditCard struct {
	gorm.Model
	Number    string
	UserRefer uint
}

func (c *CreditCard) TableName() string {
	return "creditcard"
}



func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	// 迁移 schema
	db.AutoMigrate(&CreditCard{})
	db.AutoMigrate(&User{})

	// Create
	/*db.Create(&User{
		Model:       gorm.Model{},
		CreditCards: []CreditCard{
			{Number: "1",UserRefer: 1},
			{Number: "2",UserRefer: 2},
			{Number: "3",UserRefer: 3},
			{Number: "4",UserRefer: 4},
		},
	})
	db.Create(&User{
		Model:       gorm.Model{ID: 2},
		CreditCards: []CreditCard{
			{Number: "1",UserRefer: 1},
			{Number: "2",UserRefer: 2},
			{Number: "3",UserRefer: 3},
			{Number: "4",UserRefer: 4},
		},
	})*/

	// Read
	var user User
	db.First(&user, 1) // 根据整形主键查找
	//db.First(&user, "number = ?", "2") // 查找 code 字段值为 D42 的记录

	b := &User{
		Model:       gorm.Model{ID: 1},
		CreditCards: nil,
	}
	err = db.Delete(b).Error
	if err != nil {
		fmt.Println(err)
	}

}